package com.up.interview.redis.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: liuchengjun
 * @title: RedissonLockImpl
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:
 * @date: 2025/10/20/周一 15:58 (星期一)
 * @since V2.0
 */
@Slf4j
@Component("redissonLock")
public class RedissonLockImpl implements DistributedLock {
    @Autowired
    private RedissonClient redissonClient;

    private final ThreadLocal<RLock> lockThreadLocal = new ThreadLocal<>();

    @Override
    public void lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        lockThreadLocal.set(lock);
        log.debug("Redisson锁加锁成功: {}", lockKey);
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        boolean acquired = lock.tryLock(waitTime, leaseTime, unit);
        if (acquired) {
            lockThreadLocal.set(lock);
            log.debug("Redisson锁尝试加锁成功: {}", lockKey);
        } else {
            log.debug("Redisson锁尝试加锁失败: {}", lockKey);
        }
        return acquired;
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = lockThreadLocal.get();
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
            lockThreadLocal.remove();
            log.debug("Redisson锁解锁成功: {}", lockKey);
        }
    }
}
